package cn.jia.hrm.service.impl;

import cn.jia.hrm.domain.LoginUser;
import cn.jia.hrm.domain.Permission;
import cn.jia.hrm.exception.AssertGlobal;
import cn.jia.hrm.mapper.LoginUserMapper;
import cn.jia.hrm.mapper.PermissionMapper;
import com.alibaba.fastjson.JSON;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Component;
import springfox.documentation.spring.web.json.Json;

import java.util.List;
import java.util.stream.Collectors;
@Component
public class MyUserDetailService implements UserDetailsService{

    @Autowired
    private LoginUserMapper loginUserMapper;
    @Autowired
    private PermissionMapper permissionMapper;
    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        System.out.println("username="+username);
        AssertGlobal.hasText(username,"用户名不能为空");
        LoginUser loginUser= loginUserMapper.seleByusername(username);

        AssertGlobal.isnull(loginUser,"用户为空");

        List<Permission> permissions = permissionMapper.selectByUserid(loginUser.getId());
        List<SimpleGrantedAuthority> authorities = permissions.stream().map(permission -> {
           //把用户的权限表达式封装成SimpleGrantedAuthority，交给Security
            return new SimpleGrantedAuthority(permission.getSn());
        }).collect(Collectors.toList());   //把一个一个权限变成一个个对象   在用list装起来collect(Collectors.toList())

        String password = loginUser.getPassword();
        loginUser.setPassword(null);
        return new User(JSON.toJSONString(loginUser),password,authorities);
    }
}
